package com.example.usermanagement.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    // 公开访问的端点
    @GetMapping("/all")
    public String allAccess() {
        return "Public Content.";
    }

    // 仅用户角色可访问的端点
    @GetMapping("/user")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public String userAccess() {
        return "User Content.";
    }

    // 仅管理员角色可访问的端点
    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String adminAccess() {
        return "Admin Content.";
    }

    // 显示所有注册的RequestMapping映射
    @GetMapping("/mappings")
    public Map<String, String> showAllMappings() {
        Map<String, String> mappings = new HashMap<>();
        
        // 获取所有RequestMappingInfo和对应的处理方法
        Map<RequestMappingInfo, HandlerMethod> allMappings = requestMappingHandlerMapping.getHandlerMethods();
        
        // 遍历并添加到结果中
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : allMappings.entrySet()) {
            RequestMappingInfo info = entry.getKey();
            HandlerMethod method = entry.getValue();
            
            // 使用第一个URL模式作为键
            String url = info.getPatternValues().iterator().next();
            String methodInfo = method.getBeanType().getSimpleName() + "." + method.getMethod().getName();
            
            mappings.put(url, methodInfo);
        }
        
        return mappings;
    }
    
    // 用于测试POST请求的端点
    @PostMapping("/echo")
    public ResponseEntity<?> echo(@RequestBody Map<String, Object> data) {
        logger.info("Received POST request with data: {}", data);
        return ResponseEntity.ok(data);
    }

}